#pragma once

#include <iostream>
#include <string>
#include <poll.h>
#include <memory>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;



const int gdefaultfd = -1;

#define MAX 4096

class PollServer
{
public:
    PollServer(int port) : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);

        for(int i = 0; i < MAX; i++)
        {
            _fds[i] .fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }

        //把唯一的fd添加进poll中
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
        //_fds[0].revents
    }
    void Loop()
    {
        int timeout = -1;
        _isrunning = true;
        while(_isrunning)
        {
            int n = poll(_fds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                std::cout << "有事件就绪... time out:" << std::endl;
                Dispatcher();
                TestFd();
                break;
            }
        }
        
    }
    void Start()
    {
        Loop();
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        // 已就绪，可以获取新连接
        SockPtr newfd = _listen_socket->Accepter(&client);
        if (newfd->Fd() < 0)
            return;
        else
        {
            std::cout << "获取了一个新连接：" << newfd->Fd() << " client info:" << client.Addr() << std::endl;
            int pos = -1;
            for (int j = 0; j < MAX; j++)
            {
                if (_fds[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == gdefaultfd)
            {
                // 被写满了
                //在poll中_fds可以自动扩容
                LOG(LogLevel::ERROR) << "服务器满载...";
                close(newfd->Fd());
            }
            else
            {
                _fds[pos].fd = newfd->Fd();
                _fds[pos].events = POLLIN;
            }

        }
    }
    void Recver(int who)
    {
         // 合法，就绪，普通fd
         char buffer[1024];
         ssize_t n = recv(_fds[who].fd, buffer, sizeof(buffer) - 1, 0); // 不会被阻塞，因为该文件描述符已经就绪
         if (n > 0)
         {
             buffer[n] = 0;
             std::cout << "client#" << buffer << std::endl;
             // 回显读到的消息
             std::string message = "echo#";
             message += buffer;
             send(_fds[who].fd, message.c_str(), message.size(), 0); // Todo
         }
         else if (n == 0)
         {
             LOG(LogLevel::DEBUG) << "客户端退出， sockfd:" << _fds[who].fd;
             close(_fds[who].fd);
             _fds[who].fd = gdefaultfd;
             _fds[who].events = _fds[who].revents = 0;
         }
         else
         {
             LOG(LogLevel::DEBUG) << "客户端读取出错， sockfd:" << _fds[who].fd;
             close(_fds[who].fd);
             _fds[who].fd = gdefaultfd;
             _fds[who].events = _fds[who].revents = 0;
         }
    }
    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;

            // 合法的文件描述符
            if (_fds[i].fd == _listen_socket->Fd()) //该fd是监听套接字（listenfd）
            {
                if (_fds[i].events & POLLIN)
                {
                    Accepter();   //获取新连接
                }
            }
            else
            {
                if (_fds[i].revents & POLLIN) //读事件就绪
                {
                   Recver(i);   //处理IO
                }
            }
        }
    }
    void TestFd()
    {
        std::cout<<"pollfd: ";
        for(int i = 0; i < MAX; i++)
        {
            if(_fds[i].fd == gdefaultfd)
                continue;
            std::cout<< _fds[i].fd << "[" << Event2Str(_fds[i].events) <<"]";
        }
        std::cout<<"\n";
    }

    std::string Event2Str(short events)
    {
        std::string s = (events & POLLIN) ? "POLLIN" : "";
        s += (events & POLLOUT) ? "POLLOUT" : "";

        return s;
    }
    ~PollServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;

    struct pollfd _fds[MAX];
};